package cn.wd.common.base.page;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @author wangdong
 * @date 2024/9/12 16:05
 **/
@Data
@Accessors(chain = true)
public class BasePlusPage implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * 页码，从1开始
     */
    private Integer pageNum = 1;

    /**
     * 每页条数
     */
    private Integer pageSize = 10;
    /**
     * 是否删除
     */
    private Boolean deleted;
    /**
     * 开始时间
     */
    private LocalDate beginTime;
    /**
     * 结束时间
     */
    private LocalDate endTime;
    /**
     * 当前记录起始索引 默认值
     */
    public static final int DEFAULT_PAGE_NUM = 1;

    /**
     * 每页显示记录数 默认值 默认查全部
     */
    public static final int DEFAULT_PAGE_SIZE = Integer.MAX_VALUE;

    /**
     * 跳过的条数
     */
    private Integer pageCount;

    public void buildPage() {
        replaceSizeNum();
        replacePageCount();
    }


    /** 替换isAsc */
    private void replaceSizeNum(){
        if (pageNum == null || pageNum < DEFAULT_PAGE_NUM) {
            pageNum = DEFAULT_PAGE_NUM;
            pageSize = DEFAULT_PAGE_SIZE;
        }
        if (pageSize == null ) {
            pageSize = DEFAULT_PAGE_SIZE;
        }
    }

    /**
     * 计算条数并赋值
     */
    private void replacePageCount(){
        pageCount = (pageNum - 1) * pageSize;
    }

    public <T> Page<T> build() {
        Integer pageNum = Objects.requireNonNullElse(getPageNum(), DEFAULT_PAGE_NUM);
        Integer pageSize = Objects.requireNonNullElse(getPageSize(), DEFAULT_PAGE_SIZE);
        if (pageNum <= 0) {
            pageNum = DEFAULT_PAGE_NUM;
        }
        return new Page<>(pageNum, pageSize);
    }

    /**
     * 计算条数并赋值
     *
     * @param pageNum
     * @param pageSize
     */
    public Integer computePageCount(Integer pageNum, Integer pageSize) {
        if (pageNum == null || pageNum <= 0) {
            return 0;
        } else {
            return (pageNum - 1) * (pageSize == null ? 0 : pageSize);
        }
    }

    public void computePageCount() {
        pageNum = (pageNum - 1) * pageSize;
    }
}
